package ycyc.ioc.core;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

import ycyc.ioc.annotation.ToBean;
import ycyc.ioc.annotation.UseBean;
import ycyc.ioc.util.PackageUtil;
import ycyc.ioc.util.PropTool;

/**
 * @author cjb
 * @date 2017-1-2
 */
public class IocListener {
	/**
	 * 销毁mgioc
	 */
	public static void destoryMgIoc() {
		IocFactory.destoryFactory();
		System.out.println("mgioc释放资源成功");
	}

	/**
	 * 初始化mgioc
	 */
	public static void initMgIoc() {
		// 扫描注解加载到ioc工厂中
		Properties prop = PropTool.use("mgwork.properties");
		// 未配置就扫描所有package
		String packageName = prop.getProperty("scan.package", "");
		List<String> classNames = PackageUtil.getClassName(packageName);
		for (String className : classNames) {
			injectToBean(className);
		}
		for (String className : classNames) {
			injectUseBean(className);
		}
		System.out.println("ioc --> " + IocFactory.toJsonString());
	}

	/**
	 * 解析ToBean注解
	 * 
	 * @param className
	 *            类名
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void injectToBean(String className) {
		try {
			Class clazz = Class.forName(className);
			// 解析类注解@ToBean
			Annotation toBean = clazz.getAnnotation(ToBean.class);
			if (null != toBean) {
				Class<?> interfaces[] = clazz.getInterfaces();//获得Dog所实现的所有接口
				Object o=clazz.newInstance();
		        for (Class<?> inte : interfaces) {//打印
		            IocFactory.add(inte.getName(),o );
		        }
		        IocFactory.add(clazz.getName(), o);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析UseBean注解
	 * 
	 * @param className
	 *            类名
	 */
	@SuppressWarnings({ "rawtypes" })
	public static void injectUseBean(String className) {
		try {
			Class clazz = Class.forName(className);
			// 解析属性注解@UseBean
			Field[] fields = clazz.getDeclaredFields();
			for (Field f : fields) {
				UseBean useBean = f.getAnnotation(UseBean.class);
				if (null != useBean) {
					f.setAccessible(true);
					f.set(IocFactory.get(clazz.getName()), IocFactory.get(f.getType().toString().split(" ")[1]));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
